package user

import (
	"context"
	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"
	"fast-boot/app/model"
	"fast-boot/common/globalkey"
	"fast-boot/common/xerr"
	"github.com/hwUltra/fb-tools/jwtx"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProfileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProfileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProfileLogic {
	return &ProfileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// Profile 获取用户
func (l *ProfileLogic) Profile() (resp *types.SysUserProfileResq, err error) {

	userId := jwtx.NewJwtX(l.ctx, l.svcCtx.Config.JwtUserKey).GetUid()
	gormDb := l.svcCtx.GormClient.GormDb
	userInfo := model.SysUserModel{}
	gormDb.Preload("Roles", "status = ?", 1).Preload("Dept", "status = 1").First(&userInfo, userId)

	if userInfo.Id == 0 {
		logx.WithContext(l.ctx).Errorf("用户不存在uid: %d", userId)
		return nil, xerr.NewErrMsg("用户不存在")
	}

	rolesName := make([]string, 0)
	for _, v := range userInfo.Roles {
		rolesName = append(rolesName, v.Name)
	}

	return &types.SysUserProfileResq{
		Id:        userId,
		Mobile:    userInfo.Mobile,
		Nickname:  userInfo.Nickname,
		Username:  userInfo.Username,
		Avatar:    userInfo.Avatar,
		RoleNames: strings.Join(rolesName, ","),
		DeptName:  userInfo.Dept.Name,
		CreatedAt: userInfo.CreatedAt.Format(globalkey.DateTimeFormatStandardTime),
		Email:     userInfo.Email,
		Gender:    int64(userInfo.Gender),
	}, nil
}
